<template>
  <el-card class="user-container">
    <!-- 头部 -->
    <div class="header">
      <el-button
        type="default"
        size="small"
        icon="el-icon-plus"
        @click="addOrEditUser(1)"
        :style="btnStyle"
      >
        新增
      </el-button>
      <el-button
        type="default"
        size="small"
        icon="el-icon-edit"
        @click="addOrEditUser(0)"
        :style="btnStyle"
      >
        编辑
      </el-button>
      <el-button
        type="default"
        size="small"
        icon="el-icon-star-off"
        @click="editUserRole"
        :style="btnStyle"
      >
        分配角色
      </el-button>
      <el-button
        type="default"
        size="small"
        icon="el-icon-delete"
        @click="delUser"
        :style="btnStyle"
      >
        批量删除
      </el-button>
    </div>
    <!-- 表格 -->
    <el-table
      stripe
      border
      ref="userTable"
      :data="userListData.users"
      tooltip-effect="dark"
      style="width: 100%"
      :style="fontStyle"
      @select="selectUser"
      @select-all="selectAllUser"
    >
      <el-table-column align="center" type="selection" width="55">
      </el-table-column>
      <el-table-column align="center" prop="username" label="姓名" width="180">
      </el-table-column>
      <el-table-column align="center" prop="email" label="邮箱" width="200">
      </el-table-column>
      <el-table-column align="center" prop="mobile" label="电话" width="200">
      </el-table-column>
      <el-table-column align="center" prop="role_name" label="角色">
      </el-table-column>
      <el-table-column
        align="center"
        prop="dateTime"
        label="创建时间"
        width="200"
      >
      </el-table-column>
      <el-table-column align="center" label="状态">
        <template slot-scope="{ row }">
          <el-switch
            v-model="row.mg_state"
            :active-color="theme.color"
            inactive-color="#ddd"
            @change="changeUserStatus(row)"
          >
          </el-switch>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <my-pagination
      :params="params"
      :total="userListData.total"
      @handleSizeChange="handleSizeChange"
      @handleCurrentChange="handleCurrentChange"
    ></my-pagination>
    <!-- 分配角色对话框 -->
    <el-dialog
      title="分配角色"
      :visible.sync="editRoleDialogVisible"
      width="30%"
      :before-close="editRoleClose"
    >
      <p>
        当前用户：<span>{{ selectedUser.username }}</span>
      </p>
      <p style="margin: 10px 0">
        当前角色：<span>{{ selectedUser.role_name }}</span>
      </p>
      <div>
        <span>分配新角色：</span>
        <el-select v-model="rid" placeholder="请选择" @change="selectRole">
          <el-option
            v-for="role in roleList"
            :key="role.id"
            :label="role.roleName"
            :value="role.id"
          >
          </el-option>
        </el-select>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editRoleClose">取 消</el-button>
        <el-button type="primary" :style="btnStyle" @click="editRoleConfirm">
          确 定
        </el-button>
      </span>
    </el-dialog>
    <!-- 新增或编辑用户对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="addOrEditDialogVisible"
      width="50%"
    >
      <el-form
        ref="addOrEditFormRef"
        :model="addOrEditFormUser"
        label-width="80px"
        :rules="addOrEditUserRules"
      >
        <el-form-item
          label="用户名"
          :prop="title === '编辑用户' ? '' : 'username'"
        >
          <el-input
            v-model="addOrEditFormUser.username"
            :disabled="title === '编辑用户'"
          ></el-input>
        </el-form-item>
        <el-form-item label="密码" v-if="title === '新增用户'" prop="password">
          <el-input v-model="addOrEditFormUser.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addOrEditFormUser.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="addOrEditFormUser.mobile"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="addOrEditUserCancel">取 消</el-button>
        <el-button
          type="primary"
          :style="btnStyle"
          @click="addOrEditUserConfirm"
        >
          确 定
        </el-button>
      </div>
    </el-dialog>
  </el-card>
</template>

<script>
import { mapState, mapActions } from 'vuex'
import myPagination from '../components/my-pagination.vue'
// 邮箱验证
const validateEmail = (rule, value, cb) => {
  const emailReg = /\w[-\w.+]*@([A-Za-z0-9][-A-Za-z0-9]+\.)+[A-Za-z]{2,14}/
  emailReg.test(value) ? cb() : cb(new Error('邮箱格式不正确'))
}
// 手机验证
const validateMobile = (rule, value, cb) => {
  const mobileReg = /^1[0-9]{10}$/
  mobileReg.test(value) ? cb() : cb(new Error('手机格式不正确'))
}
export default {
  components: { myPagination },
  name: 'user',
  data() {
    return {
      // 获取用户列表参数
      params: {
        query: '',
        pagenum: 1,
        pagesize: 5,
      },
      selectedUser: {}, // 当前选中的用户
      selectedUserList: [], // 选中的用户列表
      editRoleDialogVisible: false, // 分配角色对话框的状态
      rid: '', // 分配角色id
      title: '新增用户', // 新增或编辑用户对话框标题
      addOrEditDialogVisible: false, // 新增或编辑用户对话框的状态
      addOrEditFormUser: {}, // 新增或编辑用户表单对象
      //新增或编辑用户表单验证规则
      addOrEditUserRules: {
        username: [
          { required: true, message: '请填写用户名', trigger: 'blur' },
          { min: 2, max: 10, message: '长度在2~10个字符之间', trigger: 'blur' },
        ],
        password: [
          { required: true, message: '请填写密码', trigger: 'blur' },
          { min: 6, max: 18, message: '长度在6~18个字符之间', trigger: 'blur' },
        ],
        // 自定义验证规则
        email: [
          { required: true, message: '请填写邮箱', trigger: 'blur' },
          { validator: validateEmail, trigger: 'change' },
        ],
        mobile: [
          { required: true, message: '请填写手机号', trigger: 'blur' },
          { validator: validateMobile, trigger: 'change' },
        ],
      },
    }
  },
  computed: {
    ...mapState('user', ['userListData']),
    ...mapState('theme', ['theme']),
    ...mapState('role', ['roleList']),
  },
  methods: {
    ...mapActions('role', ['getRoleList']),
    // 获取用户列表
    async getUserList() {
      await this.$store.dispatch('user/getUserList', this.params)
    },
    // 改变用户状态的回调
    async changeUserStatus(user) {
      try {
        const params = { uId: user.id, type: user.mg_state }
        await this.$store.dispatch('user/editUserStatus', params)
        this.$message.success('修改用户状态成功')
      } catch (error) {
        this.$message.error(error)
      }
    },
    /**
     * 勾选用户回调
     * selection 已被选中的用户
     * row 当前点击的用户
     */
    selectUser(selection, row) {
      this.selectedUserList = selection
      this.selectedUser = selection[selection.length - 1]
    },
    // 选中所有用户
    selectAllUser(selection) {
      this.selectedUserList = selection
    },
    // 判断是否有用户被勾选
    userSelectStatus() {
      if (!this.selectedUser.username) {
        return this.$message.info('请选中一个用户')
      }
      if (this.selectedUserList.length > 1) {
        return this.$message.info('至多选中一个用户')
      }
      return false
    },
    // 选择角色的回调
    selectRole(rid) {
      this.rid = rid
    },
    // 编辑用户角色（打开编辑角色对话框）
    editUserRole() {
      // 未选择用户
      if (this.userSelectStatus()) return
      // 显示对话款，获取角色列表
      this.editRoleDialogVisible = true
      this.getRoleList()
    },
    // 点击分配角色确定按钮的回调
    async editRoleConfirm() {
      if (!this.rid) return this.$message.info('请选择角色')

      try {
        const params = {
          id: this.selectedUser.id,
          rid: this.rid,
        }
        await this.$store.dispatch('user/editUserRole', params)
        await this.$store.dispatch('user/getUserList', this.params)
        this.$message.success('分配角色成功')
        this.editRoleDialogVisible = false
        this.rid = ''
        this.selectedUser = {}
      } catch (error) {
        console.log(error)
      }
    },
    // 关闭编辑角色对话框的回调
    editRoleClose() {
      this.editRoleDialogVisible = false
      // 清除残留的数据
      this.rid = ''
      this.selectedUser = {}
      // 清除选择项
      this.$refs.userTable.clearSelection()
    },
    // 清空新增或编辑用户表单数据
    clearAddOrEditUserForm() {
      this.$refs.addOrEditFormRef.resetFields()
      this.addOrEditFormUser = {}
    },
    /**
     * 点击新增或编辑用户的回调
     * type 1表新增，0表编辑
     */
    addOrEditUser(type) {
      if (type === 1) {
        // 无论是否有勾选，先清空勾选的用户
        this.$refs.userTable.clearSelection()
        this.selectedUser = {}
        this.selectedUserList = []
        this.title = '新增用户'
      } else {
        // 判断是否选择一个用户
        if (this.userSelectStatus()) return
        this.title = '编辑用户'
      }
      this.addOrEditDialogVisible = true
      this.$refs.addOrEditFormRef.resetFields()
      this.addOrEditFormUser = JSON.parse(JSON.stringify(this.selectedUser))
    },
    // 点击添加或编辑用户取消按钮的回调
    addOrEditUserCancel() {
      this.clearAddOrEditUserForm()
      this.addOrEditDialogVisible = false
    },
    // 点击添加或编辑用户确定按钮的回调
    addOrEditUserConfirm() {
      this.$refs.addOrEditFormRef.validate(async v => {
        if (!v) return
        try {
          const params = {
            id: this.selectedUser.id,
            user: this.addOrEditFormUser,
          }
          await this.$store.dispatch('user/addOrEditUser', params)
          await this.$store.dispatch('user/getUserList', this.params)
          this.$message.success(this.title + '成功')
          this.addOrEditDialogVisible = false
          this.clearAddOrEditUserForm()
        } catch (error) {
          console.log(error)
        }
      })
    },
    // 点击批量删除用户
    async delUser() {
      if (this.selectedUserList.length <= 0) {
        return this.$message.info('请选择要删除的用户')
      }
      try {
        await this.$store.dispatch('user/deleteUser', this.selectedUserList)
        await this.$store.dispatch('user/getUserList', this.params)
        this.$message.success('删除用户成功')
      } catch (error) {
        console.log(error)
      }
    },
    // 改变页面数量的回调
    handleSizeChange(pageSize) {
      const { params } = this
      params.pagesize = pageSize
      this.getUserList()
    },
    // 改变页码的回调
    handleCurrentChange(currentPage) {
      const { params } = this
      params.pagenum = currentPage
      this.getUserList()
    },
  },
  mounted() {
    this.getUserList()

    this.$on('handleSizeChange', this.handleSizeChange)
    this.$on('handleCurrentChange', this.handleCurrentChange)
  },
}
</script>

<style lang="scss" scoped>
.el-card {
  text-align: center;
  .header {
    margin-bottom: 10px;
    text-align: left;
  }
}
</style>
